package com.shengxing.lljl.service.impl;

import com.shengxing.lljl.dto.UserDto;
import com.shengxing.lljl.entity.User;
import com.shengxing.lljl.mapper.UserMapper;
import com.shengxing.lljl.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shengxing.lljl.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表-存储用户信息 服务实现类
 * </p>
 *
 * @author 小邹
 * @since 2024-10-17
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    UserMapper userMapper;


    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public User loginService(User user) {

        User user1 = userMapper.findByEmail(user.getEmail());
        if(user1 == null){
            //用户不存在
            return null;
        }else{
            if(user1.getPassword().equals(user.getPassword())){
                //登录成功
                return user1;
            }else{
                //密码错误
                return null;
            }
        }

    }

    @Override
    public String save(UserDto userDto) {
        //1,验证邮箱码
        String storedCode = redisTemplate.opsForValue().get(userDto.getEmail());
        //1.1失败，直接返回
        if (!userDto.getCode().equals(storedCode)) {
            // 邮箱码验证失败
            return "EMAILCODEERROR";
        } else {
            //1.2成功，注册
            User user = new User();
            BeanUtils.copyProperties(userDto, user);
            //新注册的账号等级是0
            user.setClazz(0);

            //1.2.1数据库没有该用户邮箱，继续注册 防止多个线程注册
            if (userMapper.findByEmail(userDto.getEmail()) == null) {
                user.setAccountFunds(BigDecimal.valueOf(0));
                int insert = userMapper.insert(user);
                if (insert == 0) {
                    return "ERROR";
                } else if (insert == 1) {
                    return "SUCCESS";
                }

            } else {
                return "EMAILEXISTS";
            }
        }

        return null;
    }

    //  没有邮箱码注册验证
//    @Override
//    public User registerService(User user) {
//        User user1 = userMapper.findByEmail(user.getEmail());
//        if(user1 == null){
//            //用户不存在，进行注册
//            int result = userMapper.insert(user);
//            if(result == 0){
//                return null;
//            }else{
//                User u = userMapper.findByEmail(user.getEmail());
//                return u;
//            }
//        }else{
//            //用户存在，前往登录
//            return null;
//        }
//
//    }

    @Override
    public String sendEmailCode(String email) {
        if (userMapper.findByEmail(email)!=null) {
            return "EMAIL_EXISTS";
        }else {
            //发送验证码
            // 生成验证码并发送邮件
            String verificationCode = UUID.randomUUID().toString().substring(0, 6); // 生成6位验证码
            sendVerificationEmail(email, verificationCode);
            // 将验证码存储到 Redis，设置过期时间10分钟，10分钟内注册有效
            // 如果10分钟内再次点击获取验证码，则生成新的验证码，删除之前的验证码
            redisTemplate.opsForValue().set(email, verificationCode, 10, TimeUnit.MINUTES);

            }


        return "SUCCESS";
    }

    @Override
    public UserVo getByEmail(String email) {
        UserVo userVo = new UserVo();
        User user = userMapper.findByEmail(email);
//        log.info("用户数据{}",user);
        if (user == null) {
            return null;
        }
        BeanUtils.copyProperties(user, userVo);
        log.info("用户数据{}",userVo);
        return userVo;
    }

    private void sendVerificationEmail(String email, String code) {
        String subject = "【流量精灵】";
        String message = "您的验证码是: " + code+"(十分钟内有效)";

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo(email);
        mailMessage.setFrom("1726912926@qq.com"); // 确保此处与用户名相同
        mailMessage.setSubject(subject);
        mailMessage.setText(message);
        mailSender.send(mailMessage);
    }

    @Override
    public Boolean updateBasicInfService(User newUser) {
        return userMapper.updateById(newUser) == 0? false: true;
    }

    @Override
    public Boolean updatePasswordService(User newUser) {
        return userMapper.updateById(newUser) == 0? false: true;
    }

    @Override
    public Boolean updateEmailService(User newUser) {
        return userMapper.updateById(newUser) == 0? false: true;
    }
}
